<?php
session_start();
include_once 'Nav.php';
$inv_date = date("Y-m-d");
?>

<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-body">
                <h4 class="header-title mb-3 size_18">新增图片</h4>

                <form class="needs-validation" action="ImgAddPost.php" method="post" enctype="multipart/form-data" 
                      onsubmit="return check()" novalidate>
                    <div class="form-group mb-3">
                        <label for="validationCustom01">日期</label>
                        <input class="form-control col-sm-4" id="example-date" type="date" name="imgDatd" 
                               value="<?php echo $inv_date ?>" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="validationCustom01">图片描述
                            <span class="margin_left badge badge-success-lighten">尽量控制在25个字符以内</span>
                        </label>
                        <input name="imgText" type="text" class="form-control" placeholder="请输入图片描述" required>
                    </div>

                    <div class="form-group mb-3">
                        <label>选择上传方式</label>
                        <select class="form-control col-sm-4" id="uploadType" onchange="toggleUploadMethod()">
                            <option value="local">本地上传</option>
                            <option value="url">URL 链接</option>
                        </select>
                    </div>

                    <!-- 本地上传 -->
                    <div class="form-group mb-3" id="local_upload">
                        <label>上传图片</label>
                        <div class="custom-file">
                            <input type="file" class="custom-file-input" id="imageUpload" name="imageFile" 
                                   accept="image/*" onchange="previewImage(this)">
                            <label class="custom-file-label" for="imageUpload">选择图片</label>
                        </div>
                        <div id="imagePreview" class="mt-2"></div>
                    </div>

                    <!-- URL上传 -->
                    <div class="form-group mb-3" id="img_url" style="display:none;">
                        <label>图片URL</label>
                        <input type="text" name="imgUrl" class="form-control" placeholder="请输入图片URL地址">
                    </div>

                    <div class="form-group mb-3 text_right">
                        <button class="btn btn-primary" type="button" id="ImgAddPost">新增相册</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
#imagePreview {
    margin-top: 10px;
    padding: 10px;
    border: 2px dashed #ddd;
    border-radius: 4px;
    min-height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

#imagePreview img {
    max-width: 200px;
    max-height: 200px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.custom-file-input:lang(zh) ~ .custom-file-label::after {
    content: "浏览";
}
</style>

<script>
function toggleUploadMethod() {
    const uploadType = document.getElementById('uploadType').value;
    const localUpload = document.getElementById('local_upload');
    const urlUpload = document.getElementById('img_url');
    
    if (uploadType === 'local') {
        localUpload.style.display = 'block';
        urlUpload.style.display = 'none';
        urlUpload.querySelector('input').required = false;
        document.getElementById('imageUpload').required = true;
    } else {
        localUpload.style.display = 'none';
        urlUpload.style.display = 'block';
        urlUpload.querySelector('input').required = true;
        document.getElementById('imageUpload').required = false;
    }
}

function previewImage(input) {
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';
    
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const img = document.createElement('img');
            img.src = e.target.result;
            preview.appendChild(img);
        }
        reader.readAsDataURL(input.files[0]);
        
        // 更新文件名显示
        const fileName = input.files[0].name;
        input.nextElementSibling.innerHTML = fileName;
    }
}

function check() {
    const imgText = document.getElementsByName('imgText')[0].value.trim();
    const uploadType = document.getElementById('uploadType').value;
    
    if (imgText.length === 0) {
        alert("图片描述不能为空");
        return false;
    }
    
    if (uploadType === 'local') {
        const fileInput = document.getElementById('imageUpload');
        if (!fileInput.files || fileInput.files.length === 0) {
            alert("请选择要上传的图片");
            return false;
        }
    } else {
        const urlInput = document.getElementsByName('imgUrl')[0];
        if (!urlInput.value.trim()) {
            alert("请输入图片URL");
            return false;
        }
    }
    
    return true;
}

// 处理表单提交
$(document).ready(function() {
    $('#ImgAddPost').click(function() {
        if (!check()) return;
        
        const formData = new FormData($('form')[0]);
        
        $.ajax({
            url: 'ImgAddPost.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                console.log("Response:", response);
                if (response == "1") {
                    alert("添加成功！");
                    window.location.href = "loveImg.php";
                } else {
                    alert("添加失败，请重试！");
                }
            },
            error: function(xhr, status, error) {
                console.error("Error:", error);
                alert("上传失败：" + error);
            }
        });
    });
});
</script>

<?php include_once 'Footer.php'; ?>
</body>
</html>